<template>
  <view class="container">
    <scroll-view scroll-y style="height:calc(100vh - 120rpx)">
      <uni-card title="受益人" extra="额外信息" v-for="(formData, index) in syr" :key="index">
        <template v-slot:title>
          <uni-list>
            <uni-list-item>
              <template v-slot:header>
                <view class="slot-box">受益人{{ index === 0 ? '' : index }}</view>
              </template>
              <template v-slot:footer>
                <uni-icons class="slot-image" type="trash-filled" size="24" @click="deleteSyr(index)"
                           v-if="index!==0"></uni-icons>
              </template>
            </uni-list-item>
          </uni-list>
        </template>
        <uni-forms :ref="'form'+index" :modelValue="syr[index]" err-show-type='modal' :rules="rules">
          <uni-forms-item label="姓名" name="name">
            <uni-easyinput type="text" v-model="syr[index].name" placeholder="请输入姓名"/>
          </uni-forms-item>
          <uni-forms-item label="关系" name="relation">
            <uni-easyinput type="text" v-model="syr[index].relation" placeholder="请输入关系"/>
          </uni-forms-item>
          <uni-forms-item label="性别" name="gender">
            <uni-data-checkbox v-model="syr[index].gender" :localdata="range"></uni-data-checkbox>
          </uni-forms-item>
          <uni-forms-item label="年龄" name="age">
            <uni-number-box v-model.number="syr[index].age"/>
          </uni-forms-item>
        </uni-forms>
      </uni-card>
    </scroll-view>
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="base" title="确认删除该受益人吗？" value="对话框预置提示内容!" placeholder="请输入内容"
                        @confirm="dialogInputConfirm"></uni-popup-dialog>
    </uni-popup>
    <view style="display: flex;justify-content: center;">
      <button class="button" type="primary" @click="addSyr">添加受益人</button>
      <button class="button" type="primary" @click="submit">下一步</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      name: '100',
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入姓名',
          }]
        },
        relation: {
          rules: [{
            required: true,
            errorMessage: '请输入关系',
          }]
        },
        age: {
          rules: [{
            required: true,
            errorMessage: '请输入年龄',
          }]
        },
      },
      syr: [],
      range: [{
        value: '男',
        text: '男'
      }, {
        value: '女',
        text: '女'
      }],
      openid: '',
      delIdx: 0,
    }
  },
  created() {
    let that = this
    uni.getStorage({
      key: 'currentUser',
      success(res) {
        console.log(123, res)
        that.openid = res.data.openid
        that.getJcrs()
      }
    })
  },
  methods: {
    getJcrs() {
      let that = this
      const db = wx.cloud.database()
      db.collection('JCRS').where({
        openid: that.openid
      }).orderBy('index', 'asc').get().then(res1 => {
        that.syr = res1.data
      })
    },

    deleteSyr(idx) {
      this.delIdx = idx
      this.$refs.inputDialog.open()
    },
    dialogInputConfirm() {
      this.syr.splice(this.delIdx, 1)
    },
    addSyr() {
      this.syr.push({
        openid: this.openid,
        name: '',
        relation: '',
        gender: '',
        age: '',
        index: ''

      })
    },
    submit() {
      let that = this
      const db = wx.cloud.database()
      const jcrs = db.collection('JCRS')

      let pass = true
      console.log(this.$refs['form0'])
      this.syr.map(async (v, index) => {
        await this.$refs['form' + index][0].validate().then(res => {
          console.log('表单数据信息：', res);
        }).catch(err => {
          console.log('表单错误信息：', err);
          pass = false
        })
      })
      if (!pass) {
        return
      }

      // 当前的逻辑是先删除，再添加数据
      db.collection('JCRS').where({
        openid: that.openid
      }).get({
        success(res) {
          let existJcrs = res.data
          console.log(existJcrs)


          that.syr.map((v, idx) => {
            if (existJcrs.map(e => e.name).includes(v.name)) {
              db.collection('JCRS').where({
                openid: that.openid,
                name: v.name
              }).update({
                data: {
                  openid: v.openid,
                  relation: v.relation,
                  gender: v.gender,
                  age: v.age,
                  index: idx
                }
              })
              //  已存在就不需再添加了，仅需要把基本的信息修改一下
            } else {
              jcrs.add({
                data: {
                  openid: v.openid,
                  name: v.name,
                  relation: v.relation,
                  gender: v.gender,
                  age: v.age,
                  index: idx
                }
              })
            }

          })
          uni.navigateTo({
            url: '/pages/101qrsyr/101qrsyr',
            success() {
              console.log('succ')
            },
            fail() {
              console.log('failed')
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: calc(100% - 40px);
}
</style>
